//
//  BHFunAddFunnyViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/24.
//  创建约玩

import UIKit
import AMapSearchKit

class BHFunAddFunnyViewController: BHBaseViewController {
    
    var completeRefreshBlock:(() -> Void)?
    

    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-BHFunCreateBottomView.height)
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var createBottomView: BHFunCreateBottomView = {
        let view = BHFunCreateBottomView.init(frame: CGRect(x: 0, y: UIScreen.height-BHFunCreateBottomView.height, width: UIScreen.width, height: BHFunCreateBottomView.height))
        return view
    }()
    
    lazy var choseTypeView: BHFunPublishTypeChoseView = {
        let view = BHFunPublishTypeChoseView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        view.delegate = self
        return view
    }()
    
    
    //0默认发布  1修改
    var type: Int = 0
    var funId: String = ""
    
    
    fileprivate let rowArray: [[BHFunCreateRowModel]] = BHFunCreateRowModel.createFun
    fileprivate var tempCreateModel: BHFunAddNewModel = BHFunAddNewModel.init()
    fileprivate var addTempModel: BHFunAddTempModel = BHFunAddTempModel.init()
    fileprivate var addImageArray: [BHImageOrVideoModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.bh_navigationBar.title_label.text = "约玩"

        self.view.addSubview(self.tableView)
        self.view.addSubview(self.createBottomView)
        self.view.addSubview(self.choseTypeView)
        self.regiseterCell()
        
        self.queryFilterTypeService(model: nil)
        
        self.createBottomView.createBtn.addBtnAction(action: {[weak self] (_) in
            self?.checkPublishInfo()
        }, for: .touchUpInside)
        
        if self.type == 1 {
            self.loadFunDetailService()
            self.createBottomView.createBtn.setTitle("立即修改", for: .normal)
        }
    }

    private func regiseterCell() {
        self.tableView.regiseterNib(nibName: "BHComInputTextCell")
        self.tableView.regiseterNib(nibName: "BHComArrowChoseCell")
        self.tableView.regiseterNib(nibName: "BHFunApplyAddressCell")
        self.tableView.regiseterNib(nibName: "BHComSwitchCell")
        self.tableView.regiseterNib(nibName: "BHComAddOrShowImageCell")
        self.tableView.regiseterNib(nibName: "BHFunDetailMoreMarkTextCell")

    }
    
    
    private func checkPublishInfo() {
        if self.addTempModel.name.isEmpty == true {
            BHToast.toast(text: "请输入约玩名称")
            return
        }
        if self.addTempModel.name.count > 15 {
            BHToast.toast(text: "约玩标题最大15字")
            return
        }
        if self.addTempModel.typeOneValue.isEmpty == true &&
            self.addTempModel.typeTwoValue.isEmpty == true {
            BHToast.toast(text: "请选择活动类型")
            return
        }
        if self.addTempModel.startTime.isEmpty == true {
            BHToast.toast(text: "请选择活动开始时间")
            return
        }
        if self.addTempModel.signupEndTime.isEmpty == true {
            BHToast.toast(text: "请选择报名截止时间")
            return
        }
        if self.addTempModel.limitPerson.isEmpty == true {
            BHToast.toast(text: "请填写活动限制人数")
            return
        }
        if Int(self.addTempModel.limitPerson)! > 200 {
            BHToast.toast(text: "活动人数最大200人")
            return
        }
        
        if self.addTempModel.placeType == 1 { // 自定义
            if self.addTempModel.address.isEmpty == true {
                BHToast.toast(text: "请关联活动地址")
                return
            }
        }else {
            if self.addTempModel.relateModel == nil {
                BHToast.toast(text: "请关联活动地址")
                return
            }
        }
        
        if self.addTempModel.ifFee == 1 {
            if self.addTempModel.price.isEmpty == true {
                BHToast.toast(text: "请输入报名费")
                return
            }
        }
        
        if self.addTempModel.contactNumber.isEmpty == true {
            BHToast.toast(text: "请填写联系方式")
            return
        }
        
        if self.addTempModel.contactNumber.count != 11 {
            BHToast.toast(text: "请输入正确的联系方式")
            return
        }
        
        let startTime = Date.transTimeToMinValue(time: self.addTempModel.startTime)
        let signEndTime = Date.transTimeToMinValue(time: self.addTempModel.signupEndTime)
        
        if startTime < signEndTime {
            BHToast.toast(text: "活动开始时间不能早于报名截止时间")
            return
        }
        
        
        if self.type == 1 {
            self.editeInfoService()

        }else {
            self.publishNewFunService()
        }
        
    }

}
extension BHFunAddFunnyViewController : BHCircleChosePlaceAreaViewControllerDelegate{
    func didChoseAddress(poi: AMapPOI?) {
        if poi != nil {
            self.addTempModel.place = poi?.name ?? ""
            self.addTempModel.address = poi?.address ?? ""
            self.addTempModel.lat = "\(poi?.location.latitude ?? 0.0)"
            self.addTempModel.log = "\(poi?.location.longitude ?? 0.0)"
            self.tableView.reloadData()
        }
    }
}

extension BHFunAddFunnyViewController: BHFunPublishTypeChoseViewDelegate {
    func didChoseLeft(model: BHCommonSortTypeModel) {
        self.queryFilterTypeService(model: model)
    }
    
    func didChoseRight(model: BHCommonSortTypeModel) {
        self.addTempModel.typeOneValue = model.parentId
        self.addTempModel.typeTwoValue = model.typeId
        self.addTempModel.typeShowName = model.text
        self.tableView.reloadData()
    }
    
    func didTypeChoseClose() {
        
    }
    
}

extension BHFunAddFunnyViewController: BHChoseFunAddressViewControllerDelegate {
    func didSelectRelateModel(model: BHFunPublishRelateModel) {
        self.addTempModel.relateModel = model
        self.addTempModel.venueId = model.venueId
        self.tableView.reloadData()
    }
}

extension BHFunAddFunnyViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.rowArray.count+1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == self.rowArray.count {
            if self.addImageArray.count >= 6   {
                return 4
            }else if self.addImageArray.count >= 3 {
                return 3
            }else {
                return 2
            }
        }else if section == 3 { // 报名费
            if self.addTempModel.ifFee == 1 {
                return 2
            }else {
                return 1
            }
        } else {
            let array = self.rowArray[section]
            return array.count
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == self.rowArray.count {
            if indexPath.row == 0 {
                return 100
            }else {
                return 120
            }
        }else if indexPath.section == 2 {
            if self.addTempModel.placeType == 0 {
                return BHFunApplyAddressCell.cellHeightWithAddress(haveAddress: self.addTempModel.relateModel != nil)
            }else {
                return BHFunApplyAddressCell.cellHeightWithAddress(haveAddress: self.addTempModel.address.isEmpty == false)
            }
        } else {
            return 53
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return CGFloat.leastNormalMagnitude
        }else {
            return 10
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
}

extension BHFunAddFunnyViewController: UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
        view.backgroundColor = .color_f8f8f8
        return view
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == self.rowArray.count {
            return self.cellForFunRemark(indexPath: indexPath)
        }else {
            let array = self.rowArray[indexPath.section]
            let model = array[indexPath.row]
            if model.type == 1 {
                return self.cellForText(indexPath: indexPath,model: model)
            }else if model.type == 2 {
                return self.cellForChoseArrow(indexPath: indexPath,model: model)
            }else if model.type == 3 {
                return self.cellForSwitch(indexPath: indexPath,model: model)
            }else if model.type == 4 {
                return self.cellForAdress(indexPath: indexPath,model: model)
            }else {
                return UITableViewCell()
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.view.endEditing(true)

        if indexPath.section >= self.rowArray.count  {
            return
        }
        
        let array = self.rowArray[indexPath.section]
        let model = array[indexPath.row]
        if model.type == 4 {
            BHCommonTool.showSheetWith(showVC: self, title: "选择活动地址", messages: ["选择场馆","自定义地址"]) {[weak self] (index) in
                if index == 0 { // 选择场馆
                    self?.addTempModel.placeType = 0
                    let choseVC = BHChoseFunAddressViewController.init()
                    choseVC.delegate = self
                    self?.navigationController?.pushViewController(choseVC, animated: true)
                }
                if index == 1 { // 自定义地址
                    self?.addTempModel.placeType = 1
                    let choseVC = BHCircleChosePlaceAreaViewController.init()
                    choseVC.weakSuper = self
                    choseVC.delegate = self
                    self?.navigationController?.pushViewController(choseVC, animated: true)
                }
            }
        }
        if model.type == 2 { // 选择活动类型
            self.choseTypeView.showOrHide(show: true)
        }
    }
}

extension BHFunAddFunnyViewController {
    func choseImageOrTake(index: Int)  {
        BHCommonTool.showPicAlert(showVC: self) { (type) in
            if type == 0 {
                BHCommonTool.init().takePhoto { (img) in
                    if img != nil {
                        self.uploadImage(image: img!)
                    }
                }
            }
            if type == 1 {
                BHCommonTool.init().photeChose(maxCount: 1) { (img,asset) in
                    if img != nil {
                        self.uploadImage(image: img!)
                    }
                }
            }
        }
    }
}

extension BHFunAddFunnyViewController {
    func cellForFunRemark(indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell : BHFunDetailMoreMarkTextCell = self.tableView.dequeueReusableCell(withIdentifier: "BHFunDetailMoreMarkTextCell", for: indexPath) as! BHFunDetailMoreMarkTextCell
            cell.text_view.text = self.addTempModel.introduce
            cell.place_label.isHidden = !self.addTempModel.introduce.isEmpty
            cell.inputTextEndCall = {[weak self] text in
                self?.addTempModel.introduce = text ?? ""
            }
            return cell
        }else {
            let cell : BHComAddOrShowImageCell = self.tableView.dequeueReusableCell(withIdentifier: "BHComAddOrShowImageCell", for: indexPath) as! BHComAddOrShowImageCell
            cell.configImage(imageArray: self.addImageArray, index: indexPath.row-1, canAdd: true)
            cell.didImageActBlock = { [weak self] (index, chose,model) in
                if chose == true {
                    BHMediaTool.showPreview(array: self?.addImageArray ?? [], current: index)
                }else {
                    self?.choseImageOrTake(index: index)
                }
            }
            cell.didDeleteImageAtIndexBlock = { [weak self] index in
                self?.addImageArray.remove(at: index)
                self?.tableView.reloadData()
            }
            return cell
        }
    }
}

extension BHFunAddFunnyViewController {
    func cellForText(indexPath: IndexPath, model: BHFunCreateRowModel) -> UITableViewCell {
        let cell : BHComInputTextCell = self.tableView.dequeueReusableCell(withIdentifier: "BHComInputTextCell", for: indexPath) as! BHComInputTextCell
        self.configeCellText(model: model, cell: cell)
        cell.model = model
        if model.canTextEdite == false {
            cell.textFiledBegainEditingBlock = { [weak self] in
                let dataPicker = EWDatePickerViewController.init(frame: UIScreen.main.bounds)
                self?.view.addSubview(dataPicker)
                /// 回调显示方法
                dataPicker.backDate = { date in
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "YYYY-MM-dd HH:mm"
                    let dateString: String = dateFormatter.string(from: date)
                    
                    self?.appendText(text: dateString, model: model)
                    
                    self?.tableView.reloadData()
                }
                /// 弹出时日期滚动到当前日期效果
                dataPicker.show()
            }
        }else {
            cell.textFiledDidEndEditingBlock = {[weak self] text in
                self?.appendText(text: text, model: model)
            }
        }
        return cell
    }
    
    func cellForChoseArrow(indexPath: IndexPath, model: BHFunCreateRowModel) -> UITableViewCell {
        let cell : BHComArrowChoseCell = self.tableView.dequeueReusableCell(withIdentifier: "BHComArrowChoseCell", for: indexPath) as! BHComArrowChoseCell
        cell.model = model
        cell.content_label.text = self.addTempModel.typeShowName
        return cell
    }
    
    
    func cellForSwitch(indexPath: IndexPath, model: BHFunCreateRowModel) -> UITableViewCell {
        let cell : BHComSwitchCell = self.tableView.dequeueReusableCell(withIdentifier: "BHComSwitchCell", for: indexPath) as! BHComSwitchCell
        cell.swithBtn.isOn = self.addTempModel.ifFee == 1
        cell.model = model
        cell.changeStateValueActBlock = {[weak self] on in
            self?.addTempModel.ifFee = on == true ? 1:0
            self?.tableView.reloadData()
        }
        return cell
    }
    
    func cellForAdress(indexPath: IndexPath, model: BHFunCreateRowModel) -> UITableViewCell {
        let cell : BHFunApplyAddressCell = self.tableView.dequeueReusableCell(withIdentifier: "BHFunApplyAddressCell", for: indexPath) as! BHFunApplyAddressCell
        if self.addTempModel.placeType == 0 {
            cell.model = self.addTempModel.relateModel
            cell.iconImgView.isHidden = false
            cell.name_leading.constant = 10
        }else {
            cell.name_label.text = self.addTempModel.place
            cell.area_label.text = self.addTempModel.address
            cell.iconImgView.isHidden = true
            cell.name_leading.constant = -50
        }
        
        return cell
    }
}

extension BHFunAddFunnyViewController {
    func appendText(text: String, model: BHFunCreateRowModel)  {
        if model.name == "活动名称" {
            self.addTempModel.name = text
        }
        
        if model.name == "活动人数限制" {
            self.addTempModel.limitPerson = text
        }
        
        if model.name == "联系方式" {
            self.addTempModel.contactNumber = text
        }
        
        if model.name == "活动开始时间" {
            let now = Date.currentMinValue
            let startTime = Date.transTimeToMinValue(time: text)
            if startTime < now {
                BHToast.toast(text: "活动开始时间不能早于当前时间")
                return
            }
            self.addTempModel.startTime = text
        }
        
        if model.name == "报名截止时间" {
            let now = Date.currentMinValue
            let signEndTime = Date.transTimeToMinValue(time: text)
            if signEndTime < now {
                BHToast.toast(text: "报名截止时间不能早于当前时间")
                return
            }
            self.addTempModel.signupEndTime = text
        }
        if model.name == "报名费（元）" {
            self.addTempModel.price = text
        }
    }
    
    func configeCellText(model: BHFunCreateRowModel,cell: BHComInputTextCell) {
        if model.name == "活动名称" {
            cell.text_filed.text = self.addTempModel.name
        }
        
        if model.name == "活动人数限制" {
            cell.text_filed.text = self.addTempModel.limitPerson

        }
        
        if model.name == "联系方式" {
            cell.text_filed.text = self.addTempModel.contactNumber

        }
        
        if model.name == "活动开始时间" {
            cell.text_filed.text = self.addTempModel.startTime

        }
        
        if model.name == "报名截止时间" {
            cell.text_filed.text = self.addTempModel.signupEndTime
        }
        if model.name == "报名费（元）" {
            cell.text_filed.text = self.addTempModel.price
        }
    }
}



extension BHFunAddFunnyViewController {
    func uploadImage(image: UIImage)  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.upload(images: [image], progressHandler: nil) { (success, errorMsg, array) in
            SVProgressHUD.dismiss()
            if success == true {
                let model = BHImageOrVideoModel.init()
                model.imageUrl = array.first
                self.addImageArray.append(model)
                
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}

// MARK: 查询类型
extension BHFunAddFunnyViewController {
    func queryFilterTypeService(model: BHCommonSortTypeModel?)  {
        if model == nil {
            BHCommonService.queryTypeOneService(type: 2) { (modelArray) in
                self.choseTypeView.leftArray = modelArray
            }
        }else {
            BHCommonService.queryTypeTwoService(parentModel: model!) { (array) in
                model?.childArray = array
                self.choseTypeView.rightTable.reloadData()
            }
        }
    }
}

// 发布新的趣玩
extension BHFunAddFunnyViewController {
    func publishNewFunService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        let dic = self.appendPublishDic()
        
        manager.post(url: String.fun_publish_url, paramters: dic) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "发布成功")
                self.completeRefreshBlock?()
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    func appendPublishDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["name"] = self.addTempModel.name
        dic["typeOneValue"] = self.addTempModel.typeOneValue
        dic["typeTwoValue"] = self.addTempModel.typeTwoValue
        dic["startTime"] = self.addTempModel.startTime
        dic["signupEndTime"] = self.addTempModel.signupEndTime
        dic["limitPerson"] = self.addTempModel.limitPerson
        dic["placeType"] = self.addTempModel.placeType
        if self.addTempModel.placeType == 0 { // 选择场馆
            dic["venueId"] = self.addTempModel.venueId
        }else {
            dic["log"] = self.addTempModel.log
            dic["lat"] = self.addTempModel.lat
            dic["place"] = self.addTempModel.place
            dic["address"] = self.addTempModel.address
        }
        dic["latitude"] = BHLocationManager.shared.latitude
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["ifFee"] = self.addTempModel.ifFee
        if self.addTempModel.ifFee == 1 {
            dic["price"] = self.addTempModel.price
        }
        dic["contactNumber"] = self.addTempModel.contactNumber
        dic["introduce"] = self.addTempModel.introduce

        let urls = BHImageOrVideoModel.transeToImageUrl(array: self.addImageArray)
        dic["urlList"] = urls
        if self.type == 1 {
            dic["id"] = self.funId
        }
        return dic
    }
    
}

extension BHFunAddFunnyViewController {
    func editeInfoService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        let dic = self.appendPublishDic()
        
        manager.put(url: String.me_fun_creater_editeDetailInfo_url, paramters: dic) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "修改成功")
                self.completeRefreshBlock?()
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}

extension BHFunAddFunnyViewController {
    func loadFunDetailService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.fun_detail_url, paramters: ["id":self.funId,"latitude":BHLocationManager.shared.latitude,"longitude":BHLocationManager.shared.longitude]) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                let resutl = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let model = BHFunDetailInfoModel.init()
                model.parseDic(resutl)
  
                self.transModel(model: model)
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    
    func transModel(model: BHFunDetailInfoModel) {
        self.addTempModel.name = model.name
        self.addTempModel.typeOneValue = model.typeOneLabel
        self.addTempModel.typeTwoValue = model.typeTwoLabel
        if model.typeTwoLabel == "" {
            self.addTempModel.typeShowName = model.typeOneLabel
        }else {
            self.addTempModel.typeShowName = model.typeTwoLabel
        }
        
        self.addTempModel.startTime = model.beginTime
        self.addTempModel.signupEndTime = model.signupEndTime
        self.addTempModel.limitPerson = "\(model.limitPerson)"
        
        if model.venueId.isEmpty == true { // 自定义场馆
//            self.addTempModel.address = model.price
            self.addTempModel.place = model.venueName
        }else {
            self.addTempModel.venueId = model.venueId
            let relateModel  = BHFunPublishRelateModel.init()
            relateModel.relationPic = model.cover
            relateModel.venueId = model.venueId
            relateModel.relationName = model.venueName
            relateModel.cityName = model.cityName
            relateModel.areaName = model.areaName
            
            self.addTempModel.relateModel = relateModel
        }
        
        if model.price.isEmpty == true ||
            model.price == "0" ||
            model.price == "0.0" ||
            model.price == "0.00" {
            self.addTempModel.ifFee = 0
        }else {
            self.addTempModel.ifFee = 1
            self.addTempModel.price = model.price
        }
        
        self.addTempModel.contactNumber = model.contactNumber
        self.addTempModel.introduce = model.introduce
        self.addImageArray = model.urlList
        
        self.tableView.reloadData()
    }
}
